//
//  MYTabBarController.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-20.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "MYTabBarController.h"
#import "MYNavigationController.h"
#import "MYHomeViewController.h"
#import "MYProfileViewController.h"
#import "MYTabBar.h"
#import "MYUnReadResult.h"
#import "MYUserTool.h"
#import "MYComposeViewController.h"

@interface MYTabBarController ()<MYTabBarDelegate, MYComposeViewControllerDelegate>
@property (nonatomic, weak) MYTabBar *currtentTabBar;
@property (nonatomic, weak) MYHomeViewController *home;
@property (nonatomic, weak) MYProfileViewController *profile;
@property (nonatomic, assign) NSInteger currUnreadStatusCount;//当前未读数
@property (nonatomic, assign) NSInteger lastUnreadStatusCount;//之前未读数

@end

@implementation MYTabBarController
// 总共的未读数 =  之前未读数 + 当前未读数

/*
 totalUnreadStatusCount = 0;
 curUnreadStatusCount = 2
 
 上啦刷新
 在上啦刷新的时候就马上记录主
 totalUnreadStatusCount = lastUnreadStatusCount(0) + currUnreadStatusCount(2);
 curUnreadStatusCount = 1
 
 只要上啦的时候,才需要记录主
 totalUnreadStatusCount = lastUnreadStatusCount(2) + curUnreadStatusCount(1) 3;
 curUnreadStatusCount = 0
 */
- (void)viewDidLoad {
    [super viewDidLoad];
    //自定义UITabBar
    MYTabBar *tabBar = [[MYTabBar alloc] initWithFrame:self.tabBar.bounds];
    tabBar.delegate = self;
    tabBar.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background"]];
#warning block的强引用
    __weak typeof(self) weakSelf = self;
    tabBar.operateBlock = ^(NSUInteger selectedIndex) {
        // 判断是否点击首页,
        if (selectedIndex == 0 && selectedIndex == weakSelf.selectedIndex) {
            [_home refresh];
        }
        weakSelf.selectedIndex = selectedIndex;
    };
    [self.tabBar addSubview:tabBar];
    self.currtentTabBar = tabBar;
//    [self.tabBar removeFromSuperview];//系统的UITabBar无法删除
    //添加所有子控制器
    [self setupAllChildVC];
    
    // 定义定时器,每隔一段时间做事情
    // 优先级低,在拖的时候,就不会触发这个定时器,想要拖动的时候,触发定时器
    // 加入主允许循环,并且设置模式为NSRunLoopCommonModes,就会让系统抽出时间来触发这个定时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(loadUnreadCount) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    // 接收上啦刷新通知
    /**
     *  self谁监听通知
     *  selector 监听到通知的时候,调用这个方法
     *  name:通知的名称
     *  object:谁发出,一般传nil,意味着不管谁发出的都监听
     */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginMore) name:MYBeginMoreNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginNew) name:MYBeginNewNote object:nil];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)beginMore
{
    // 记录上一次总共未读数
    self.lastUnreadStatusCount = _lastUnreadStatusCount + _currUnreadStatusCount;
}
- (void)beginNew
{
    self.lastUnreadStatusCount = 0;
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    // 没有调用系统默认的做法,添加UITabBarButton
//    [super viewWillAppear:animated];
//    // 删除self.tabBar中的子控件除了自定义tabBar
//    for (UIView *childView in self.tabBar.subviews) {
//        if (![childView isKindOfClass:[MYTabBar class]]) { // 不是自己的tabBar
//            [childView removeFromSuperview];
//        }
//    }
//
//}
- (void)viewWillLayoutSubviews
{
    // 没有调用系统默认的做法,添加UITabBarButton
    [super viewWillLayoutSubviews];
    // 删除self.tabBar中的子控件除了自定义tabBar
    for (UIView *childView in self.tabBar.subviews) {
        if (![childView isKindOfClass:[MYTabBar class]]) { // 不是自己的tabBar
            [childView removeFromSuperview];
        }
    }
}

//加载未读数
- (void)loadUnreadCount
{
    [MYUserTool unReadCountDidSuccess:^(MYUnReadResult *unReadResult) {
         // 设置首页的奇闻未读数
        self.currUnreadStatusCount = unReadResult.status;
        _home.tabBarItem.badgeValue = [NSString stringWithFormat:@"%zi", self.currUnreadStatusCount + self.lastUnreadStatusCount];
        // 设置我的未读数
        _profile.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i", unReadResult.follower];
        // 设置桌面提醒数字
        [UIApplication sharedApplication].applicationIconBadgeNumber = unReadResult.totalCount;
    } failure:^(NSError *error) {
//        MYLog(@"%@", error);
    }];
}
#pragma mark - 添加所有子控制器
- (void)setupAllChildVC
{
    //添加一个子控制器
    //首页
    MYHomeViewController *home = [[MYHomeViewController alloc] init];
    [self setupOneChildVC:home title:@"首页" image:[UIImage imageNamed:@"tabbar_home"] selectedImage:[UIImage imageNamed:@"tabbar_home_selected"]];
    self.home = home;
    //我
    MYProfileViewController *profile = [[MYProfileViewController alloc] init];
    [self setupOneChildVC:profile title:@"我" image:[UIImage imageNamed:@"tabbar_profile"] selectedImage:[UIImage imageNamed:@"tabbar_profile_selected"]];
    self.profile = profile;
    
}
#pragma mark - 添加一个子控制器
- (void)setupOneChildVC:(UIViewController *)viewController title:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage
{
    viewController.title = title;
    viewController.tabBarItem.image = image;
#warning iOS7默认会把tabBar上按钮的选中图片渲染成蓝色
    selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//不进行渲染
    viewController.tabBarItem.selectedImage = selectedImage;
    MYNavigationController *navVC = [[MYNavigationController alloc] initWithRootViewController:viewController];
    [self addChildViewController:navVC];
    [self.currtentTabBar addTabBarButton:viewController.tabBarItem];
}
#pragma mark - 代理方法
- (void)tabBarDidClickaddButton:(MYTabBar *)tabBar
{
    MYComposeViewController *composeVC = [[MYComposeViewController alloc] init];
    composeVC.delegate = self;
    MYNavigationController *navVC = [[MYNavigationController alloc] initWithRootViewController:composeVC];
    [self presentViewController:navVC animated:YES completion:nil];
}
- (void)composeViewControllerDidCancle:(MYComposeViewController *)composeViewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
